<template>
  <div class="order-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">订单管理</h2>
      <p class="page-desc">管理所有订单信息，支持筛选、编辑和删除</p>
    </div>

    <!-- 操作栏：筛选+搜索 -->
    <div class="operation-bar">
      <el-select
        v-model="statusFilter"
        placeholder="订单状态筛选"
        class="status-select"
        @change="handleFilter"
        :disabled="isSubmitting"
      >
        <el-option label="全部" value=""></el-option>
        <el-option label="待发货" value="待发货"></el-option>
        <el-option label="已发货" value="已发货"></el-option>
      </el-select>

      <el-input
        v-model="searchText"
        placeholder="搜索订单号/用户名"
        prefix-icon="el-icon-search"
        class="search-input"
        @keyup.enter.native="handleFilter"
        :disabled="isSubmitting"
      ></el-input>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-state">
      <el-loading-spinner></el-loading-spinner>
      <p>正在加载订单数据...</p>
    </div>

    <!-- 订单表格 -->
    <el-table
      v-else
      :data="filteredOrders"
      border
      stripe
      style="width: 100%; background: #fff; border-radius: 8px; margin: 20px 0;"
      empty-text="暂无匹配订单数据"
      :loading="isSubmitting"
      loading-text="处理中..."
    >
      <el-table-column
        prop="id"
        label="订单id"
        width="180"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="orderNo"
        label="订单编号"
        width="180"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        width="120"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="amount"
        label="订单金额"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          ¥{{ scope.row.amount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="订单状态"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          <!-- 状态切换中显示加载动画 -->
          <el-tag
            :type="getStatusTagType(scope.row.status)"
            :loading="scope.row.isEditing"
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          <!-- 同一订单防止重复编辑 -->
          <el-button
            type="text"
            size="small"
            class="edit-btn"
            @click="openEditDialog(scope.row)"
            :disabled="isSubmitting || scope.row.isEditing"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            class="delete-btn"
            @click="showDeleteConfirm(scope.row.id)"
            :disabled="isSubmitting || scope.row.isEditing"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div v-if="!isLoading && totalOrders > 0" class="pagination">
      <el-pagination
        layout="prev, pager, next, sizes, ->, total"
        :total="totalOrders"
        :page-size.sync="pageSize"
        :current-page.sync="currentPage"
        :page-sizes="[10, 20, 50]"
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :disabled="isSubmitting"
      ></el-pagination>
    </div>

    <!-- 编辑订单弹窗 -->
    <el-dialog
      title="编辑订单状态"
      :visible.sync="editDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
    >
      <el-form
        :model="currentOrder"
        ref="orderForm"
        label-width="120px"
        :rules="orderFormRules"
        :disabled="isSubmitting"
      >
        <el-form-item label="订单id">
          <el-input v-model="currentOrder.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="currentOrder.orderNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="currentOrder.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="订单金额">
          <el-input v-model="currentOrder.amount" disabled prefix-icon="el-icon-money"></el-input>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTagType(currentOrder.originalStatus)">
            {{ getStatusText(currentOrder.originalStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="修改为" prop="status">
          <el-select v-model="currentOrder.status" placeholder="请选择订单状态">
            <el-option label="已发货" value="已发货"></el-option>
            <el-option label="待发货" value="待发货"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false" :disabled="isSubmitting">取消</el-button>
        <el-button
          type="primary"
          @click="saveOrderEdit"
          :loading="isSubmitting"
        >
          {{ isSubmitting ? '提交中...' : '保存修改' }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="300px"
      :close-on-click-modal="false"
    >
      <p>确定要删除此订单吗？删除后不可恢复</p>
      <div slot="footer">
        <el-button @click="deleteDialogVisible = false" :disabled="isSubmitting">取消</el-button>
        <el-button
          type="danger"
          @click="confirmDelete"
          :loading="isSubmitting"
        >
          {{ isSubmitting ? '删除中...' : '确认删除' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'OrderManagement',
  data() {
    return {
      orders: [], // 订单数组
      currentPage: 1,
      pageSize: 10,
      totalOrders: 0, // 总订单数
      statusFilter: '',
      searchText: '',
      editDialogVisible: false,
      deleteDialogVisible: false,
      currentOrder: {}, // 编辑中的订单
      orderIdToDelete: null,
      isLoading: false,
      isSubmitting: false, // 提交中状态（防止重复操作）
      orderFormRules: {
        status: [
          { required: true, message: '请选择订单状态', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              // 禁止选择与原状态相同的值
              if (value === this.currentOrder.originalStatus) {
                callback(new Error('新状态不能与当前状态相同'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      },
       statusConfig: {
        '已发货': { text: '已发货', type: 'info', value: 'shipped' },
        '待发货': { text: '待发货', type: 'warning', value: 'unship' },
        'shipped': { text: '已发货', type: 'info', value: 'shipped' },
        'unship': { text: '待发货', type: 'warning', value: 'unship' },
        'default': { text: '未知状态', type: 'default', value: 'unship' }
      }
    }
  },
  computed: {
    filteredOrders() {
      return this.orders.filter(order => {
        if (this.statusFilter && order.status !== this.statusFilter) return false
        if (this.searchText) {
          const lowerSearch = this.searchText.toLowerCase()
          const matchOrderNo = order.orderNo.toLowerCase().includes(lowerSearch)
          const matchUsername = order.username.toLowerCase().includes(lowerSearch)
          return matchOrderNo || matchUsername
        }
        return true
      })
    }
  },
  mounted() {
    this.getOrders()
  },
  methods: {
    /**
     * 自动适配后端数据格式
     */
    async getOrders(page = this.currentPage, size = this.pageSize) {
      this.isLoading = true
      this.isSubmitting = true
      try {
        const res = await this.$axios.get(
          `http://127.0.0.1:8000/order/?page=${page}&page_size=${size}`
        )

        if (!res || !res.data) {
          throw new Error('后端返回数据为空')
        }

        const responseData = res.data
        let orderList = []
        let totalCount = 0

        if (Array.isArray(responseData)) {
          orderList = responseData
          totalCount = responseData.length
        } else if (typeof responseData === 'object') {
          const arrayFields = ['results', 'list', 'data', 'items']
          const targetField = arrayFields.find(field => Array.isArray(responseData[field]))

          if (targetField) {
            orderList = responseData[targetField]
            totalCount = responseData.count || responseData.total || responseData.totalCount || 0
          } else {
            orderList = [responseData]
            totalCount = 1
          }
        }

        if (!Array.isArray(orderList)) {
          throw new Error('后端返回的订单数据不是数组类型')
        }

        // 新增isEditing状态（标记订单是否正在编辑）
        this.orders = orderList.map(order => this.mapOrderData(order))

        this.totalOrders = totalCount
        this.$message.success(`成功加载 ${this.orders.length} 条订单`)
      } catch (error) {
        this.orders = []
        this.totalOrders = 0
        this.$message.error(`订单加载失败：${error.message}`)
      } finally {
        this.isLoading = false
        this.isSubmitting = false
      }
    },

    // 时间格式化
    formatTime(timeStr) {
      if (!timeStr) return ''
      try {
        const date = new Date(timeStr)
        // 处理Invalid Date情况
        if (isNaN(date.getTime())) return '无效时间'
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
      } catch (e) {
        return '无效时间'
      }
    },

    // 映射订单数据
    mapOrderData(order) {
  const mappedOrder = {
    id: order.id || '',
    orderNo: order.order_number || '未知订单号',
    username: order.user?.username || '未知用户',
    createTime: order.created_at ? this.formatTime(order.created_at) : '未知时间',
    amount: Number(order.total_amount) || 0,
    status: order.status || 'unship',
    isEditing: false
  }
  return mappedOrder
},

    // 修改 getStatusText 方法，增加调试信息
getStatusText(status) {
  const result = this.statusConfig[status]?.text || this.statusConfig.default.text;
  return result;
},

// 修改 getStatusTagType 方法
getStatusTagType(status) {
  const result = this.statusConfig[status]?.type || this.statusConfig.default.type;
  return result;
},
    // 打开编辑弹窗：记录原始状态，标记编辑中
    openEditDialog(order) {
      this.currentOrder = { ...order, originalStatus: order.status }
      const index = this.orders.findIndex(item => item.id === order.id)
      if (index !== -1) {
        this.orders[index].isEditing = true
      }
      this.editDialogVisible = true
    },

    // 保存订单编辑
    // 修改保存订单编辑方法
    async saveOrderEdit() {
  const _this = this;
  this.$refs.orderForm.validate(async function(isValid) {
    if (!isValid) return;

    _this.isSubmitting = true;
    const orderIndex = _this.orders.findIndex(function(item) {
      return item.id === _this.currentOrder.id;
    });

    try {
      // 调用后端新接口
      const response = await _this.$axios.put(
        `http://127.0.0.1:8000/order/${_this.currentOrder.id}/status`,
        { status: _this.currentOrder.status }
      );

      if (orderIndex !== -1) {
        const newStatus = _this.getKeyByValue(_this.statusConfig, _this.currentOrder.status, 'value');
        _this.orders[orderIndex].status = newStatus || _this.currentOrder.status;
        _this.orders[orderIndex].isEditing = false;
        _this.$set(_this.orders, orderIndex, JSON.parse(JSON.stringify(_this.orders[orderIndex])));
      }

      _this.$message.success('订单状态修改成功');
      _this.editDialogVisible = false;
    } catch (error) {
      if (orderIndex !== -1) {
        _this.orders[orderIndex].isEditing = false;
        _this.$set(_this.orders, orderIndex, JSON.parse(JSON.stringify(_this.orders[orderIndex])));
      }
      const errorResponse = error.response || {};
      const errorData = errorResponse.data || {};
      const errorMsg = errorData.message || error.message || '未知错误';
      _this.$message.error(`订单修改失败：${errorMsg}`);
    } finally {
      _this.isSubmitting = false;
    }
  });
},

getKeyByValue(obj, value, keyName) {
  for (const key in obj) {
    if (obj.hasOwnProperty(key) && obj[key][keyName] === value) {
      return obj[key].label;
    }
  }
  return null;
},



    // 弹窗关闭时：取消编辑中标记
    handleDialogClose() {
      if (this.currentOrder.id) {
        const index = this.orders.findIndex(item => item.id === this.currentOrder.id)
        if (index !== -1) {
          this.orders[index].isEditing = false
        }
      }
      this.editDialogVisible = false
    },

    // 显示删除确认
    showDeleteConfirm(id) {
      this.orderIdToDelete = id
      this.deleteDialogVisible = true
    },

    // 确认删除
    async confirmDelete() {
      if (!this.orderIdToDelete) return

      this.isSubmitting = true
      const originalTotal = this.totalOrders
      try {
        await this.$axios.delete(
          `http://127.0.0.1:8000/order/${this.orderIdToDelete}/`
        )
        this.orders = this.orders.filter(item => item.id !== this.orderIdToDelete)
        this.totalOrders--
        this.$message.success('订单删除成功')
        this.deleteDialogVisible = false
      } catch (error) {
        this.totalOrders = originalTotal
        const errorMsg = error.response?.data?.message || error.message || '未知错误'
        this.$message.error(`订单删除失败：${errorMsg}`)
      } finally {
        this.isSubmitting = false
      }
    },

    // 筛选条件变化
    handleFilter() {
      this.currentPage = 1
      this.getOrders()
    },

    // 每页条数变化
    handlePageSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.getOrders()
    },

    // 当前页码变化
    handleCurrentPageChange(page) {
      this.currentPage = page
      this.getOrders()
    }
  }
}
</script>

<style scoped>
.order-management {
  padding: 24px;
  background-color: #f9f7f5;
  min-height: calc(100vh - 64px);
  box-sizing: border-box;
}
.page-header {
  margin-bottom: 24px;
}
.page-title {
  font-size: 20px;
  color: #3d2314;
  margin: 0 0 8px;
  font-weight: 600;
}
.page-desc {
  font-size: 14px;
  color: #8b5a2b;
  margin: 0;
}
.operation-bar {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 8px;
}
.status-select {
  width: 180px;
}
.search-input {
  width: 300px;
}
.loading-state {
  text-align: center;
  padding: 80px 0;
  background-color: #fff;
  border-radius: 8px;
  color: #8b5a2b;
}
.loading-state .el-loading-spinner {
  margin-bottom: 16px;
  font-size: 32px;
}
.el-table th {
  background-color: #f5f2ed;
  color: #3d2314;
  font-weight: 500;
}
.edit-btn {
  color: #8b5a2b !important;
}
.delete-btn {
  color: #e63946 !important;
}
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 16px;
}
.el-pagination {
  color: #8b5a2b;
}
.el-pagination .el-pager li.active {
  background-color: #8b5a2b;
  color: #fff;
}
/* 编辑中状态的按钮样式 */
.el-button:disabled.edit-btn {
  color: #c4a886 !important;
  cursor: not-allowed;
}
.el-button:disabled.delete-btn {
  color: #e8a0a6 !important;
  cursor: not-allowed;
}
@media (max-width: 768px) {
  .order-management {
    padding: 16px;
  }
  .status-select, .search-input {
    width: 100%;
  }
  .el-table {
    font-size: 13px;
  }
  .el-table-column {
    width: auto !important;
  }
}
</style>
